package com.yunc.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunc.base.utils.R;
import com.yunc.modules.sys.entity.SysDept;
import com.yunc.modules.sys.entity.SysRoleDept;
import com.yunc.modules.sys.service.ISysDeptService;
import com.yunc.modules.sys.service.ISysRoleDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色部门数据权限
 *
 * @author congcong tao
 * @create 2020/1/8 16:20
 */
@RestController
@RequestMapping("sysRoleDept")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysRoleDeptController {

    private final ISysDeptService sysDeptService;
    private final ISysRoleDeptService sysRoleDeptService;

    @GetMapping("/list")
    public R list(Long roleId) {
        // 查询出部门树
        List<SysDept> sysDeptList = sysDeptService.queryDeptList("");
        // 当前用户拥有的部门
        List<String> resultList;
        if (roleId != null) {
            QueryWrapper<SysRoleDept> ew = new QueryWrapper<>();
            ew.eq("role_id", roleId);
            List<SysRoleDept> sysRoleDeptList = sysRoleDeptService.list(ew);
            resultList = sysRoleDeptList.stream().map(SysRoleDept::getDeptId).collect(Collectors.toList());
        } else {
            resultList = new ArrayList<>();
        }
        return R.ok().put("sysDeptList", sysDeptList).put("checkDeptIdList", resultList);
    }

    @PutMapping(value = "/update")
    public R update(@NotBlank String id, @NotBlank String dataScope, String deptIds) {
        return sysRoleDeptService.updateRole(id, dataScope, deptIds);
    }
}
